package com.bobo.dao.admin;

import com.bobo.dao.BaseDao;
import com.bobo.model.Admin;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by bobo on 2016/10/24.
 */
public class AdminDaoImpl extends BaseDao<Admin> implements IAdminDao {
    @Override
    public Integer create(Admin admin) {

        String sql = "INSERT INTO t_admin(name,password,level)VALUES(?,?,?)";
        return create(sql, admin.getName(), admin.getPassword(),admin.getLevel());
    }

    @Override
    public boolean upd(Admin admin) {
        String sql = "UPDATE t_admin SET name=?,password=?,level=? where id=?";

        return update(sql, admin.getName(), admin.getPassword(), admin.getLevel(), admin.getId());
    }

    @Override
    public Admin getAdmin(Integer id) {
        String sql = "SELECT a.id,a.`name`,a.`level` FROM t_admin a WHERE a.id=?";
        Admin admin = new Admin();
        ResultSet rs = getObject(sql, id);
        try {
            while (rs.next()) {
                admin.setId(rs.getInt("id"));
                admin.setName(rs.getString("name"));
                admin.setLevel(rs.getInt("level"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return admin;
    }

    @Override
    public List<Admin> getAdmins() {
        String sql = "SELECT a.id,a.`name`,a.`level` FROM t_admin a ";
        List<Admin> admins = new ArrayList<>();
        ResultSet rs = pager(sql, 0, 0);
        try {
            while (rs.next()) {
                Admin admin = new Admin();
                admin.setId(rs.getInt("id"));
                admin.setName(rs.getString("name"));
                admin.setLevel(rs.getInt("level"));
                admins.add(admin);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return admins;
    }

    @Override
    public Admin adminCompare(String name, String password) {
        String sql = "SELECT a.id,a.`name`,a.`level` FROM t_admin a WHERE a.name=? and a.password=?";
        Admin admin = null;
        ResultSet rs = getObject(sql, name, password);
        try {
            while (rs.next()) {
                admin = new Admin();
                admin.setId(rs.getInt("id"));
                admin.setName(rs.getString("name"));
                admin.setLevel(rs.getInt("level"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return admin;
    }
}
